<template>
  <div class="example-table-page">
    <!-- 头部 -->
    <div class="header">
      <div class="header-content">
        <div class="title-section">
          <h1 class="page-title">通用表格示例</h1>
          <div class="divider"></div>
          <span class="subtitle">Total: {{ state.totalItems }}</span>
        </div>
        <div class="action-group">
          <el-input
            v-model="searchKeyword"
            placeholder="输入搜索关键字"
            clearable
            @input="handleSearch"
            class="search-input"
            size="large"
          >
            <template #prefix>
              <el-icon class="search-icon"><Search /></el-icon>
            </template>
          </el-input>
          <el-button type="primary" size="large" @click="addItem">新增</el-button>
        </div>
      </div>
    </div>

    <!-- 使用通用表格组件 -->
    <div class="table-container">
      <BaseTable
        tableName="example-table"
        :columns="tableColumns"
        :data="state.pageData"
        :loading="state.loading"
        :sort="{ field: state.sortField, order: state.sortOrder }"
        @sort-change="handleSortChange"
      >
        <!-- 自定义列内容 -->
        <template #status="{ row }">
          <el-tag :type="row.status === 1 ? 'success' : 'danger'">
            {{ row.status === 1 ? '启用' : '停用' }}
          </el-tag>
        </template>
        
        <template #createTime="{ row }">
          {{ formatTime(row.createTime) }}
        </template>
        
        <template #updateTime="{ row }">
          {{ formatTime(row.updateTime) }}
        </template>
        
        <template #actions="{ row }">
          <el-button size="small" @click="editItem(row)">编辑</el-button>
          <el-button size="small" type="danger" @click="deleteItem(row)">删除</el-button>
        </template>
      </BaseTable>
    </div>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="state.currentPage"
        v-model:page-size="state.pageSize"
        :page-sizes="[20, 50, 100, 200]"
        :total="state.totalItems"
        layout="total, sizes, prev, pager, next, jumper"
        @current-change="handlePageChange"
        @size-change="handleSizeChange"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { Search } from '@element-plus/icons-vue'
import BaseTable from '@/components/tools/BaseTable.vue'
import useTable from '@/composables/useTable.js'
import { formatTime } from '@/utils/formatter.js'

// 模拟API调用
const mockFetchData = async (params) => {
  // 模拟网络延迟
  await new Promise(resolve => setTimeout(resolve, 500))
  
  // 模拟数据
  const mockData = Array.from({ length: 100 }, (_, index) => ({
    id: index + 1,
    name: `用户${index + 1}`,
    email: `user${index + 1}@example.com`,
    phone: `138${String(index + 1).padStart(8, '0')}`,
    status: Math.random() > 0.5 ? 1 : 0,
    createTime: new Date(Date.now() - Math.random() * 30 * 24 * 60 * 60 * 1000).toISOString(),
    updateTime: new Date(Date.now() - Math.random() * 7 * 24 * 60 * 60 * 1000).toISOString()
  }))
  
  // 模拟分页
  const { pageNum, pageSize, keyword } = params
  let filteredData = mockData
  
  if (keyword) {
    filteredData = mockData.filter(item => 
      item.name.includes(keyword) || 
      item.email.includes(keyword)
    )
  }
  
  const start = (pageNum - 1) * pageSize
  const end = start + pageSize
  const records = filteredData.slice(start, end)
  
  return {
    records,
    total: filteredData.length
  }
}

// 使用通用表格组合式API
const {
  state,
  loadData,
  handleSortChange,
  updateSearchParams,
  resetSearchParams
} = useTable(mockFetchData)

// 搜索关键字
const searchKeyword = ref('')

// 表格列配置
const tableColumns = ref([
  {
    prop: 'id',
    label: 'ID',
    width: 80,
    visible: true,
    sortable: true,
    align: 'center'
  },
  {
    prop: 'name',
    label: '姓名',
    minwidth: 120,
    visible: true,
    sortable: true
  },
  {
    prop: 'email',
    label: '邮箱',
    minwidth: 200,
    visible: true,
    sortable: true
  },
  {
    prop: 'phone',
    label: '电话',
    width: 150,
    visible: true
  },
  {
    prop: 'status',
    label: '状态',
    width: 100,
    visible: true,
    slot: 'status',
    align: 'center'
  },
  {
    prop: 'createTime',
    label: '创建时间',
    width: 180,
    visible: true,
    sortable: true,
    slot: 'createTime'
  },
  {
    prop: 'updateTime',
    label: '更新时间',
    width: 180,
    visible: true,
    sortable: true,
    slot: 'updateTime'
  },
  {
    prop: 'actions',
    label: '操作',
    width: 150,
    visible: true,
    slot: 'actions',
    fixed: 'right',
    align: 'center'
  }
])

// 搜索处理
const handleSearch = () => {
  updateSearchParams({ keyword: searchKeyword.value })
}

// 分页处理
const handlePageChange = (page) => {
  state.currentPage = page
  loadData()
}

const handleSizeChange = (size) => {
  state.pageSize = size
  state.currentPage = 1
  loadData()
}

// 业务方法
const addItem = () => {
  console.log('新增项目')
}

const editItem = (row) => {
  console.log('编辑项目:', row)
}

const deleteItem = (row) => {
  console.log('删除项目:', row)
}

// 初始化
onMounted(() => {
  loadData()
})
</script>

<style scoped>
.example-table-page {
  padding: 20px;
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.header {
  background: white;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title-section {
  display: flex;
  align-items: center;
  gap: 15px;
}

.page-title {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: #2c3e50;
}

.divider {
  width: 2px;
  height: 24px;
  background: #e1e8ed;
}

.subtitle {
  color: #7f8c8d;
  font-size: 14px;
}

.action-group {
  display: flex;
  gap: 15px;
  align-items: center;
}

.search-input {
  width: 300px;
}

.search-icon {
  color: #7f8c8d;
}

.table-container {
  flex: 1;
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.pagination-container {
  background: white;
  border-radius: 8px;
  padding: 20px;
  margin-top: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  display: flex;
  justify-content: center;
}
</style> 